package com.jspgou.cms.action.admin.main;

import static com.jspgou.common.page.SimplePage.cpn;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jspgou.cms.entity.Balance;
import com.jspgou.cms.entity.BalanceVo;
import com.jspgou.cms.entity.Order;
import com.jspgou.cms.manager.BalanceMng;
import com.jspgou.cms.manager.OrderMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.manager.StoreMng;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.util.ExportExcel;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.LogMng;
import com.jspgou.core.web.SiteUtils;
import com.jspgou.core.web.WebErrors;

@Controller
public class BalanceAct {
	private static final Logger log = LoggerFactory.getLogger(BalanceAct.class);
	
	@RequestMapping("/balance/v_list.do")
	public String list(Integer pageNo, HttpServletRequest request, ModelMap model) {
		Pagination pagination =storeMng.getPage(null,true,cpn(pageNo), CookieUtils
				.getPageSize(request));
		model.addAttribute("pagination",pagination);
		model.addAttribute("pageNo",pageNo);
		return "balance/list";
	}
	
	@RequestMapping("/balance/v_notelist.do")
	public String notelist(String storeName,Date startTime,Date endTime,Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Pagination pagination =manager.getPage(null,storeName,startTime,endTime,cpn(pageNo), CookieUtils
				.getPageSize(request));
		model.addAttribute("pagination",pagination);
		model.addAttribute("storeName",storeName);
		model.addAttribute("startTime",startTime);
		model.addAttribute("endTime",endTime);
		model.addAttribute("pageNo",pageNo);
		return "balance/notelist";
	}
	
	@RequestMapping(value ="/balance/v_excel.do")
	public void excel(String storeName,Date startTime,Date endTime,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		Website web = SiteUtils.getWeb(request);
        List<Balance> list= manager.getList(storeName, startTime, endTime);
        List<BalanceVo> listVo=new ArrayList<BalanceVo>();
        for(Balance balance:list){
        	BalanceVo bv=new BalanceVo();
        	bv.setCode(balance.getStore().getCode());
        	bv.setCommission(balance.getCommission());
        	bv.setEndTime(balance.getEndTime());
        	bv.setStartTime(balance.getStartTime());
        	bv.setPlatTotal(balance.getPlatTotal());
        	bv.setStoreTotal(balance.getStoreTotal());
        	bv.setTotal(balance.getTotal());
        	bv.setStoreName(balance.getStore().getStoreName());
        	listVo.add(bv);
        }
        
	    //构造输出对象，可以从response输出，直接向用户提供下载   
	    response.setContentType("application/vnd.ms-excel;charset=gbk");
	    response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("结算报表.xls", "UTF-8"));
        OutputStream out = response.getOutputStream(); 
        ExportExcel<BalanceVo> ex = new ExportExcel<BalanceVo>();   
        String[] heads={"店铺编码","店铺名称","结算总额","抽成比例","店铺收入","平台商收入","结算开始时间","结算结束时间",};
        logMng.operating(request, "导出财务信息", "name="+storeName);
        ex.exportExcel(heads, listVo, out) ;
	}
	
	@RequestMapping("/balance/v_balance.do")
	public String balance(Long storeId,Date startTime,Date endTime,
			Integer pageNo, HttpServletRequest request,ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		List<Order> list =orderMng.getList(web.getId(), null, storeId, 4,2, null, null, null,
				null, startTime, endTime, null, null);
		Double total=0.0;
		for(Order order:list){
			total+=order.getTotal();
		}
		model.addAttribute("total",total);
		model.addAttribute("list",list);
		model.addAttribute("pageNo",pageNo);
		model.addAttribute("storeId",storeId);
		model.addAttribute("startTime",startTime);
		model.addAttribute("endTime",endTime);
		return "balance/orderList";
	}

	@RequestMapping("/balance/v_add.do")
	public String add(ModelMap model) {
		return "balance/add";
	}

	@RequestMapping("/balance/v_edit.do")
	public String edit(Long id, Integer pageNo, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("balance", manager.findById(id));
		model.addAttribute("pageNo", pageNo);
		return "balance/edit";
	}

	@RequestMapping("/balance/o_save.do")
	public String save(Balance bean,Long storeId,Date startTime,Date  endTime,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		if(startTime==null&&endTime==null){
			errors.addErrorString(productMng.getTipFile("Please.settlement"));
			return errors.showErrorPage(model);
		}
		if(startTime==null||endTime==null){
		      List<Order> list =orderMng.getList(web.getId(), null, storeId, 4,2, null, null, null,
				   null, startTime, endTime, null, null);
		      if(list.size()>0){
		    	  if(startTime==null){
		    		  startTime=list.get(list.size()-1).getCreateTime();
		    		  bean.setStartTime(startTime);
		    	  }
		           if(endTime==null){
		        	   endTime=list.get(0).getCreateTime();
		        	   bean.setEndTime(endTime);
		           }
		      }
		}
		bean.setStore(storeMng.findById(storeId));
		bean = manager.save(bean);
		log.info("save Balance id={}", bean.getId());
		logMng.operating(request, "保存店铺余额", "id="+bean.getId()+" ;name="+bean.getStore().getStoreName());
		return "redirect:v_list.do";
	}

	@RequestMapping("/balance/o_update.do")
	public String update(Balance bean, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.update(bean);
		log.info("update Balance id={}.", bean.getId());
		logMng.operating(request, "更改店铺余额", "id="+bean.getId()+" ;name="+bean.getStore().getStoreName());
		return list(pageNo, request, model);
	}

	@RequestMapping("/balance/o_delete.do")
	public String delete(Long[] ids, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Balance[] beans = manager.deleteByIds(ids);
		for (Balance bean : beans) {
			log.info("delete Balance id={}", bean.getId());
			logMng.operating(request, "删除店铺余额", "id="+bean.getId()+" ;name="+bean.getStore().getStoreName());
		}
		return list(pageNo, request, model);
	}

	private WebErrors validateSave(Balance bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
//		Website web = SiteUtils.getWeb(request);
//		bean.setWebsite(web);
		return errors;
	}
	
	private WebErrors validateEdit(Long id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (vldExist(id, web.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Long id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (vldExist(id, web.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateDelete(Long[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		errors.ifEmpty(ids, "ids");
		for (Long id : ids) {
			vldExist(id, web.getId(), errors);
		}
		return errors;
	}

	private boolean vldExist(Long id, Long webId, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Balance entity = manager.findById(id);
		if(errors.ifNotExist(entity, Balance.class, id)) {
			return true;
		}
//		if (!entity.getWebsite().getId().equals(webId)) {
//			errors.notInWeb(Balance.class, id);
//			return true;
//		}
		return false;
	}
	
	@Autowired
	private ProductMng productMng;
	@Autowired
	private BalanceMng manager;
	@Autowired
	private StoreMng storeMng;
	@Autowired
	private OrderMng orderMng;
	@Autowired
	private LogMng logMng;
}